﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Syspetro.Core;
using Syspetro.Core.DynamicApi;
using Syspetro.Core.Localization;
using Syspetro.Deploy.Middleware;
using System;
using System.Net;

namespace Syspetro.Deploy
{
    public static class ApplicationBuilder
    {
        public static IApplicationBuilder UseSyspetro(this IApplicationBuilder app)
        {
            #region 跨域设置
            app.UseCors("allowAll");
            #endregion

            app.UsePreOptionRequest();
            app.UseMiddleware(typeof(ErrorHandling));
            //app.UseMiddleware<RequestMiddleware>();

            app.UseHealthCheckMiddleware();
            //app.UseHttpsRedirection();
            app.UseLocalizationLanguages();
            // 使用静态文件
            app.UseStaticFiles();
            app.UseRouting();
            if (InternalApp.IsAuth)
            {
                app.UseAuthentication();//鉴权
            }
            app.UseAuthorization();//授权
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            if (InternalApp.Env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    foreach (var group in DynamicApiGroups.GroupExtraInfos)
                    {
                        c.SwaggerEndpoint($"/swagger/{group.Group}/swagger.json", group.Title);
                    }
                });
            }
            return app;
        }

        /// <summary>
        /// 默认的心跳响应
        /// </summary>
        /// <param name="app"></param>
        /// <param name="checkPath"></param>
        public static void UseHealthCheckMiddleware(this IApplicationBuilder app, string checkPath = "/Health")
        {
            app.Map(checkPath, applicationBuilder => applicationBuilder.Run(async context =>
            {
                Console.WriteLine($"This is Health Check");
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                await context.Response.WriteAsync("OK");
            }));
        }
    }
}
